<template>
  <div class="app-container">
    <h1 style="text-align: center;">待采购商品列表</h1>
    <DaiItem></DaiItem>
    <hr>
    <h1 style="text-align: center;">采购单</h1>
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="管理员名字
" prop="adminName">
        <el-input v-model="queryParams.adminName" placeholder="请输入管理员名字
" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="申请时间" style="width: 308px">
        <el-date-picker v-model="daterangeApplicationTime" value-format="YYYY-MM-DD" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="采购金额" prop="amount">
        <el-input v-model="queryParams.amount" placeholder="请输入采购金额" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['procurement:procurement:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['procurement:procurement:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['procurement:procurement:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['procurement:procurement:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="procurementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="采购信息清单ID" align="center" prop="listId" />
      <el-table-column label="管理员名字
" align="center" prop="adminName" />
      <el-table-column label="申请时间" align="center" prop="applicationTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applicationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购金额" align="center" prop="amount" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['procurement:procurement:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['procurement:procurement:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改存储采购信息清单的对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="procurementRef" :model="form" :rules="rules" label-width="80px">
       <div style="width: 150px;
       height: 30px;border: 5px solid dashed;">采购金额:{{ form.amount }}</div>
        <el-divider content-position="center">存储采购清单中的商品信息信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddProcurementItems">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteProcurementItems">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="procurementItemsList" :row-class-name="rowProcurementItemsIndex"
          @selection-change="handleProcurementItemsSelectionChange" ref="procurementItems" >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50" />
          <el-table-column label="变种商品ID" prop="variantId" width="300">
            <template #default="scope">
              <!-- <el-input v-model="scope.row.variantId" placeholder="请输入商品ID" /> -->
              <el-tree-select v-model="scope.row.variantId" :data="data2" :render-after-expand="false" style="width: 230px" @change="handleChange(scope.row.variantId,scope.row.index)" />
            </template>
          </el-table-column>
          <el-table-column label="价格" prop="price" width="150">
            <template #default="scope">
              {{ scope.row.price }} 元
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="quantity" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.quantity" placeholder="请输入数量" @input="handleChangePrice(scope.row.index)" />
            </template>
          </el-table-column>
          <el-table-column label="总价" prop="totalPrice" width="150">
            <template #default="scope">
              {{ scope.row.totalPrice }} 元
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Procurement">

import { listProcurement, getProcurement, delProcurement, addProcurement, updateProcurement,getTree,getVariantsProduct } from "@/api/procurement/procurement";

import DaiItem from "./DaiItem.vue";
const { proxy } = getCurrentInstance();

const procurementList = ref([]);
const procurementItemsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedProcurementItems = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeApplicationTime = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    adminName: null,
    applicationTime: null,
    amount: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询存储采购信息清单的列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeApplicationTime && '' != daterangeApplicationTime) {
    queryParams.value.params["beginApplicationTime"] = daterangeApplicationTime.value[0];
    queryParams.value.params["endApplicationTime"] = daterangeApplicationTime.value[1];
  }
  listProcurement(queryParams.value).then(response => {
    procurementList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    listId: null,
    adminName: null,
    applicationTime: null,
    amount: null
  };
  procurementItemsList.value = [];
  proxy.resetForm("procurementRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeApplicationTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.listId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加存储采购信息清单的";
  form.value.amount=0
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _listId = row.listId || ids.value
  getProcurement(_listId).then(response => {
    form.value = response.data;
    procurementItemsList.value = response.data.procurementItemsList;
    open.value = true;
    title.value = "修改存储采购信息清单的";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["procurementRef"].validate(valid => {
    if (valid) {
      form.value.procurementItemsList = procurementItemsList.value;
      if (form.value.listId != null) {
        updateProcurement(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProcurement(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _listIds = row.listId || ids.value;
  proxy.$modal.confirm('是否确认删除存储采购信息清单的编号为"' + _listIds + '"的数据项？').then(function () {
    return delProcurement(_listIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 存储采购清单中的商品信息序号 */
function rowProcurementItemsIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 存储采购清单中的商品信息添加按钮操作 */
function handleAddProcurementItems() {
  let obj = {};
  obj.variantId = "";
  obj.price = "";
  obj.quantity = "";
  obj.totalPrice = "";
  procurementItemsList.value.push(obj);
}

function handleChangePrice(index){
  console.log(111111111111111111)
 procurementItemsList.value[index-1].totalPrice= procurementItemsList.value[index-1].price*procurementItemsList.value[index-1].quantity;
  form.value.amount=0

 //计算总价
 for(let i=0;i<procurementItemsList.value.length;i++){
    console.log(procurementItemsList.value[i])
   form.value.amount=form.value.amount+procurementItemsList.value[i].totalPrice;
  
 }

}


/** 存储采购清单中的商品信息删除按钮操作 */
function handleDeleteProcurementItems() {
  if (checkedProcurementItems.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的存储采购清单中的商品信息数据");
  } else {
    const procurementItemss = procurementItemsList.value;
    const checkedProcurementItemss = checkedProcurementItems.value;
    procurementItemsList.value = procurementItemss.filter(function (item) {
      return checkedProcurementItemss.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleProcurementItemsSelectionChange(selection) {
  checkedProcurementItems.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('procurement/procurement/export', {
    ...queryParams.value
  }, `procurement_${new Date().getTime()}.xlsx`)
}


let data2=[]
function getOptions() {
  getTree().then(response => {
    data2 = response.data;
  });
}
function handleChange(vid,index){
  getVariantsProduct(vid).then(response => {
    console.log(response.data)
    procurementItemsList.value[index-1].price=response.data.price;
    procurementItemsList.value[index-1].quantity=0;
    procurementItemsList.value[index-1].totalPrice=0;
  })
  console.log("hand index:"+index)
  handleChangePrice(index)
 
}
getOptions();
getList();
</script>
